package com.android.calldelay;





import java.util.Calendar;

import com.android.calldelay.services.ServiceForCallingStateRecever;

import com.android.calldelay.alarmServices.SetAlarmService;
import com.android.calldelay.R;


import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements
android.view.View.OnClickListener {

	private static final int PICK_CONTACT_SECOND = 1;
	private static final int PICK_CONTACT_FIRST = 0;
	static final String CALL_DELAYED_FIRST_NUMBER = "CALL_DELAYED_FIRST_NUMBER";
	static final String CALL_DELAYED_SECOND_NUMBER = "CALL_DELAYED_SECOND_NUMBER";
	private static final String LOG_TAG = "MainActivity";
	private static final int PICK_CONTACT_ONE = 100;
	private static final int DEMO_REQUEST_CODE = 10;
	private static final int PICK_CONTACT_TWO = 110;
	private ContentResolver cr;
	private EditText etFirstContact;
	private EditText etSecondContact;
	/*
	 * private EditText etMinuts; private EditText etSecond;
	 */
	private EditText etMinuts;
	private EditText etSecond;
	public static String FIRST_NUMBER_TO_CALL = null;
	int couter = 0;
	private int totalSecond;
	private Bundle phoneBundle;
	private String phoneNumber = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_page_1);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		/*
		int SDK_INT = android.os.Build.VERSION.SDK_INT;
		if (SDK_INT>8){
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy); 
		}*/
		setUpView();
	}

	private void setUpView() {

		cr = getContentResolver();
		Typeface typeface = Typeface.createFromAsset(getAssets(),
				"font/arial.ttf");
		Button btnFirstContact = (Button) this.findViewById(R.id.button_first);
		Button btnSecondContact = (Button) this
				.findViewById(R.id.button_second);
		Button btnStartAlarm = (Button) this.findViewById(R.id.button_start);
		Button btnStopAlarm = (Button) this.findViewById(R.id.button_stop);
		Button btnSetUpActivity = (Button) this.findViewById(R.id.button_setup);
		Button btnwhatis = (Button) this.findViewById(R.id.button_whatis);
		etFirstContact = (EditText) this
				.findViewById(R.id.editText_first_number);
		etSecondContact = (EditText) this
				.findViewById(R.id.editText_second_number);
		TextView tvPeopleToCall 		= (TextView) this.findViewById(R.id.txt_select_people_to_call);
		TextView tvTimeBeforCalling 	= (TextView) this.findViewById(R.id.txt_time_before_calling);
		TextView tvMinutes 				= (TextView) this.findViewById(R.id.txt_minutes);
		TextView tvSeconds 				= (TextView) this.findViewById(R.id.txt_seconds);

		etFirstContact.setText(getStringData(AppInfo.KEY_FIRST_NUMBER_KEY));
		etSecondContact.setText(getStringData(AppInfo.KEY_SECOND_NUMBER_KEY));
		/*
		 * etMinuts = (EditText) this.findViewById(R.id.editText_min); etSecond
		 * = (EditText) this.findViewById(R.id.editText_second);
		 */
		etMinuts = (EditText) this.findViewById(R.id.editText_min);
		etSecond = (EditText) this.findViewById(R.id.editText_second);

		etMinuts.setText(getStringData(AppInfo.KEY_MINUTS_STRING)
				.equalsIgnoreCase("") ? "0"
						: getStringData(AppInfo.KEY_MINUTS_STRING));
		etSecond.setText(getStringData(AppInfo.KEY_SECENDS_STRING)
				.equalsIgnoreCase("") ? "0"
						: getStringData(AppInfo.KEY_SECENDS_STRING));


		etFirstContact.setTypeface(typeface);
		etSecondContact.setTypeface(typeface);
		etMinuts.setTypeface(typeface);
		etSecond.setTypeface(typeface);
		btnStartAlarm.setTypeface(typeface);
		btnStopAlarm.setTypeface(typeface);
		tvPeopleToCall.setTypeface(typeface);
		tvTimeBeforCalling.setTypeface(typeface);
		tvMinutes.setTypeface(typeface);
		tvSeconds.setTypeface(typeface);
		etMinuts.setTextAppearance(this, R.style.large_body_text);
		etSecond.setTextAppearance(this, R.style.large_body_text);





		btnFirstContact.setOnClickListener(this);
		btnSecondContact.setOnClickListener(this);
		btnStartAlarm.setOnClickListener(this);
		btnStopAlarm.setOnClickListener(this);
		btnSetUpActivity.setOnClickListener(this);
		btnwhatis.setOnClickListener(this);

		etFirstContact
		.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub

				if (hasFocus) {
					etFirstContact.setHint("");
				} else {
					etFirstContact.setHint("Primary Contact");
				}
			}
		});

		etSecondContact
		.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub

				if (hasFocus) {
					etSecondContact.setHint("");
				} else {
					etSecondContact.setHint("Secondry Contact");
				}
			}
		});

		// Button btnRandamNumberValidate =
		// (Button)this.findViewById(R.id.button_randam_number_validate_button);
		// btnRandamNumberValidate .setOnClickListener(this);
		// etRamdamInput
		// =(EditText)this.findViewById(R.id.editText_randam_number_input);
		// tvRandamNumberText =
		// (TextView)this.findViewById(R.id.tv_randam_number_text);
		// linearLayoutCaptchaValidationToolbar =
		// (LinearLayout)this.findViewById(R.id.linerlayout_captcha_code_validation_toolbar);

	}

	protected void setDialogValue(final View v) {
		// TODO Auto-generated method stub

		AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
		builder.setTitle(v.getTag().toString());
		final String[] items = new String[60];
		for (int i = 0; i < items.length; i++) {
			items[i] = "" + i;
		}
		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				((TextView) v).setText(items[which]);
			}
		});
		builder.create().show();
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button_first:

			Intent pickContactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
			// Show user only contacts w/ phone numbers
			startActivityForResult(pickContactIntent, PICK_CONTACT_ONE);


			break;

		case R.id.button_second:

			Intent pickContactIntent1 = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
			// Show user only contacts w/ phone numbers
			startActivityForResult(pickContactIntent1, PICK_CONTACT_TWO);


			break;

		case R.id.button_start:
			String firstNumber = etFirstContact.getText().toString();
			String secondNumber = etSecondContact.getText().toString();
			if (isValidNumber(firstNumber, secondNumber)) {

				String minutString = etMinuts.getText().toString();
				String secondString = etSecond.getText().toString();
				if (isInputValid(minutString, secondString)) {
					try {


						/*
						 * setRedialfuntion
						 */
						setRedialValueToStaticValue();

						int min = Integer.parseInt(minutString);
						int second = Integer.parseInt(secondString);
						totalSecond = min * 60 + second;
						saveInPrefrences(AppInfo.KEY_MINUTS_STRING, minutString);
						saveInPrefrences(AppInfo.KEY_SECENDS_STRING,
								secondString);
						saveInIntegerPrefrences(AppInfo.KEY_TOTAL_DIAL_TIME,
								totalSecond);
						int totalDialTime = getIntegerData(AppInfo.KEY_TOTAL_DIAL_TIME);
						int totalAlertTime = getIntegerData(AppInfo.KEY_TOTAL_ALERT_TIME);
						Log.d(LOG_TAG, "totalAlertTime :::" + totalAlertTime);
						Log.d(LOG_TAG, "totalDialTime :::" + totalDialTime);
						SetAlarmService alarmService  = new  SetAlarmService(v.getContext());
						if (totalAlertTime == 0 && totalDialTime == 0) {
							setData(v, firstNumber, secondNumber);
							if (getCheckedState(AppInfo.KEY_ALERT_CHECKBOX)) {
								alarmService.setupAlarm(totalDialTime - totalAlertTime);
								//setupAlarm(totalDialTime - totalAlertTime);
							}
						}

						else if (totalAlertTime != 0
								&& totalDialTime > totalAlertTime) {
							setData(v, firstNumber, secondNumber);
							if (getCheckedState(AppInfo.KEY_ALERT_CHECKBOX)) {
								alarmService.setupAlarm(totalDialTime - totalAlertTime);
								//setupAlarm(totalDialTime - totalAlertTime);
							}
						} else if (totalDialTime != 0
								&& totalDialTime > totalAlertTime) {
							setData(v, firstNumber, secondNumber);

							if (getCheckedState(AppInfo.KEY_ALERT_CHECKBOX)) {
								alarmService.setupAlarm(totalDialTime - totalAlertTime);
								//setupAlarm(totalDialTime - totalAlertTime);
							}
						} else {
							showToast("enter valid time");
						}



					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("" + e);
					}

				}

			}

			break;

		case R.id.button_stop:

			if (getCheckedState(AppInfo.KEY_PASS_CHECKBOX)) {
				showPasswordAlert(v.getId());
			} else {


				//setupAlarm(totalSecond, phoneBundle, false);
				SetAlarmService alarmService  = new  SetAlarmService(v.getContext());
				saveInBooleanPrefrences(AppInfo.KEY_CALL_DELAY_APP_START_STOP, false);
				//alarmService.setupAlarm(totalSecond, phoneBundle, false);
				alarmService.setupAlarm(false);
			}
			break;

		case R.id.button_setup:
			if (AppInfo.FLAG_ALARM_START) {
				if (getCheckedState(AppInfo.KEY_PASS_CHECKBOX)) {
					showPasswordAlert(v.getId());
				} else {

					moveToSetUpActivity(v.getContext());
				}
			}else {
				showToast("App is running so first stop the app");
			}


			break;
		case R.id.button_whatis:
			// startActivity(new Intent(v.getContext(), DemoActivity.class));

			Intent intentAboutUs = new Intent(v.getContext(),
					WhatIsActivity.class);
			startActivity(intentAboutUs);

			break;
		case R.id.editText_min:
			// startActivity(new Intent(v.getContext(), DemoActivity.class));
			setDialogValue(v);
			break;
		case R.id.editText_second:
			// startActivity(new Intent(v.getContext(), DemoActivity.class));
			setDialogValue(v);
			break;

		default:
			break;
		}
	}



	private void setRedialValueToStaticValue() {
		// TODO Auto-generated method stub
		int dialAttemptsFromPref = getIntegerData(AppInfo.KEY_DIAL_ATTEMPTS_KEY);
		/*
		  	if (dialAttemptsFromPref <= 2) {
					AppInfo.FLAG = true;
					AppInfo.COUNT = 1;
				}else*/
		AppInfo.DIAL_ATTEMPTS = dialAttemptsFromPref+1;
		AppInfo.COUNT = 0;



		// set dialing attempts value to static value for the redial in Phonestate listener
		//AppInfo.DIAL_ATTEMPTS = dialingAttempts+1;
		/* set the counter value to count;
		 * when count = 0 then send message funtion will call and after send the message set 
		 * the count to 1; if count value set to 1, then message will not send
		 * we use this varible to breack the infinite message sending
		 */
		//
		System.out.println("AppInfo.DIAL_ATTEMPTS  "+AppInfo.DIAL_ATTEMPTS +" AppInfo.COUNT"+AppInfo.COUNT);
	}

	private void setData(View v, String firstNumber, String secondNumber) {

		phoneBundle = new Bundle();

		phoneBundle.putString(CALL_DELAYED_FIRST_NUMBER, firstNumber);
		phoneBundle.putString(CALL_DELAYED_SECOND_NUMBER, secondNumber);

		//setupAlarm(totalSecond, phoneBundle, true);

		/*
		 * store first number in shared preferences to get in home screen
		 */


		saveInPrefrences(AppInfo.KEY_FIRST_NUMBER_KEY, firstNumber);
		saveInPrefrences(AppInfo.KEY_SECOND_NUMBER_KEY, secondNumber);
		SetAlarmService alarmService  = new  SetAlarmService(v.getContext());
		saveInBooleanPrefrences(AppInfo.KEY_CALL_DELAY_APP_START_STOP, true);
		//alarmService.setupAlarm(totalSecond, phoneBundle, true);
		alarmService.setupAlarm(true);

		/*
		 * Update the app widget with new number
		 */
		/*Intent intent4 = new Intent(this, CallDelayedAppWidgetProvider.class);
		intent4.setAction("android.appwidget.action.APPWIDGET_UPDATE");
		// Use an array and EXTRA_APPWIDGET_IDS instead of
		// AppWidgetManager.EXTRA_APPWIDGET_ID,
		// since it seems the onUpdate() is only fired on that:
		int ids[] = AppWidgetManager.getInstance(getApplication())
				.getAppWidgetIds(
						new ComponentName(getApplication(),
								CallDelayedAppWidgetProvider.class));

		intent4.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
		sendBroadcast(intent4);*/
		//	showToast("Call delayed is applied...");
		updateWidget(firstNumber);



	}


	private void updateWidget(String firstNumber) {
		RemoteViews localRemoteViews = new RemoteViews(this.getPackageName(),R.layout.call_delayed_appwidget_layout);
		localRemoteViews.setViewVisibility(R.id.btn_widget_delayapp_start, View.GONE);
		localRemoteViews.setViewVisibility(R.id.textView_title, View.VISIBLE);
		localRemoteViews.setTextViewText(R.id.textView_title, firstNumber);
		ComponentName localComponentName = new ComponentName(this, CallDelayedAppWidgetProvider.class);
		AppWidgetManager.getInstance(this).updateAppWidget(localComponentName, localRemoteViews);

	}

	private boolean isValidNumber(final String firstNumber, String secondNumber) {
		// TODO Auto-generated method stub
		if (firstNumber.trim().length() < 1) {
			showToast("Please Select the primary number");
			return false;
		} else if (secondNumber.length() < 1) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					MainActivity.this);
			builder.setTitle("Second Number");
			builder.setMessage("Please select a second number or click 'use only one number'");
			builder.setPositiveButton("use only one number",
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					etSecondContact.setText(firstNumber);
				}
			});
			builder.setNegativeButton("Select from Contact list",
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub

					Intent pickContactIntent1 = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
					// Show user only contacts w/ phone numbers
					startActivityForResult(pickContactIntent1, PICK_CONTACT_TWO);


				}
			});
			builder.create().show();

			return false;
		} else {

			return true;
		}

	}

	// getting the status of check box
	private boolean getCheckedState(String key) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		return setting.getBoolean(key, false);
	}

	// dialog for stopping the delay
	private void showPasswordAlert(final int id) {
		DisplayMetrics displayMetrics = getSystemDisplay();
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layoutDialog = inflater.inflate(R.layout.layout_stop_dialog, null);
		final EditText etPassword = (EditText) layoutDialog
				.findViewById(R.id.editText_password);
		Button btnOk = (Button) layoutDialog.findViewById(R.id.btn_ok);
		Button btnCancel = (Button) layoutDialog.findViewById(R.id.btn_cancel);

		int displayHeight = displayMetrics.heightPixels;
		int displayWidth = displayMetrics.widthPixels;
		final Dialog dialog = new Dialog(MainActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

		dialog.setContentView(layoutDialog, new LayoutParams(displayWidth - 20,
				displayHeight / 3));
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable());
		dialog.show();
		btnOk.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String password = etPassword.getText().toString();
				String savedPassword = getStringData(AppInfo.KEY_PASSWORD);
				Animation shake = null;
				if (password.equals(savedPassword)) {
					if (id == R.id.button_stop) {
						dialog.dismiss();
						saveInBooleanPrefrences(AppInfo.KEY_CALL_DELAY_APP_START_STOP, false);
						//new SetAlarmService(v.getContext()).setupAlarm(totalSecond, phoneBundle, false);
						//setupAlarm(totalSecond, phoneBundle, false);
						new SetAlarmService(v.getContext()).setupAlarm(false);
					} else if (id == R.id.button_setup) {

						dialog.dismiss();
						moveToSetUpActivity(v.getContext());

					}



				} else {
					shake = AnimationUtils.loadAnimation(MainActivity.this,
							R.anim.shake);
					etPassword.startAnimation(shake);
					etPassword.setError("Invalid Password");
				}
			}
		});

		btnCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

	}

	// getting the string data from preferences
	private String getStringData(String key) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		return setting.getString(key, "");
	}

	// method for saving integer data in shared preferences
	private void saveInIntegerPrefrences(String key, int value) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		Editor editor = setting.edit();
		editor.putInt(key, value);
		editor.commit();
	}

	// getting the Integer data from preferences
	private int getIntegerData(String key) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		return setting.getInt(key, 0);
	}

	// getting the system display

	private DisplayMetrics getSystemDisplay() {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		return displayMetrics;

	}

	// toast
	private void showToast(String message) {
		Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
	}

	// moving to another activity
	private void moveToSetUpActivity(Context context) {
		Intent intent = new Intent(context, SetUpActivity.class);
		intent.putExtra("TotalSeconds", totalSecond);
		startActivity(intent);

	}

	// method for saving string data in shared preferences
	private void saveInPrefrences(String key, String value) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		Editor editor = setting.edit();
		editor.putString(key, value);
		editor.commit();
	}

	private void saveInBooleanPrefrences(String keyCallDelayAppStartStop,
			boolean isStart) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		Editor editor = setting.edit();
		editor.putBoolean(AppInfo.KEY_CALL_DELAY_APP_START_STOP, isStart) ;
		editor.commit();

	}

	private boolean isInputValid(String minStr, String secStr) {
		int minutes = 0;
		int seconds = 0;
		try {
			minutes = Integer.parseInt(minStr);
			seconds = Integer.parseInt(secStr);
		} catch (Exception e) {
			Log.e(LOG_TAG, "Parsing Eception ::" + e.getMessage());
			showToast("Enter valid Values");
			return false;

		}

		if (minStr.trim().length() < 0) {
			showToast("Enter Minutes");
			return false;
		} else {

			if (secStr.trim().length() < 0) {
				showToast("Enter Seconds");
				return false;
			} else {

				if (minutes >= 60) {
					showToast("Enter valid value in Minutes");
					return false;
				} else {

					if (seconds >= 60) {
						showToast("Enter valid value in Second");
						return false;
					} else {

						return true;
					}

				}
			}

		}

	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			getContact(data);

			switch (requestCode) {
			case PICK_CONTACT_ONE: 
				etFirstContact.setText(phoneNumber);
				break;
			case PICK_CONTACT_TWO: 
				etSecondContact.setText(phoneNumber);
				break;

			}
		}

	}


	// getting the contact from the conatct list
	private void getContact(Intent data) {
		Cursor cursor = null;  

		try {  
			Uri result = data.getData();  
			String id = result.getLastPathSegment();  

			cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,  
					null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[] { id },  
					null);  
			int phoneNumberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
			if (cursor.moveToFirst()) {  
				phoneNumber = cursor.getString(phoneNumberIndex);  
				Log.v(LOG_TAG, " phoneNumber is ::::::: " + phoneNumber);  

			} else {  
				Log.w(LOG_TAG, "No results");  
			}  

		}catch (Exception e) {
			Log.e(LOG_TAG, "Exception :"+e.getMessage());
		}finally{
			if (cursor!=null) {
				cursor.close();
			}
		} 

	}

}